package com.acme.ionio.impl;

import com.acme.ionio.FileCopierServer;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Gregory Sobko
 */
public class FileCopierServerIO implements FileCopierServer {
    private static Logger logger = Logger.getLogger(FileCopierServerIO.class);

    @Override
    public void copy(File to, int port) throws IOException {
        logger.info("Waiting for user connection...");
        try(ServerSocket serverSocket = new ServerSocket(port);
        Socket socket = serverSocket.accept();
            PrintWriter clientWriter = new PrintWriter(socket.getOutputStream());
            DataInputStream is = new DataInputStream(socket.getInputStream());
            FileOutputStream fos = new FileOutputStream(to)){
            logger.info("User connected!");
            byte[] buffer = new byte[65536];
            int bytesRead = 0;
            logger.debug("Reading filesize...");
            long total = is.readLong();
            logger.debug("Bytes to read: " + total);
            try{
                while ((bytesRead = is.read(buffer)) != -1 ){
                    fos.write(buffer, 0, bytesRead);
                    total -= bytesRead;
                    if(total == 0){
                        break;
                    }
                }
            }catch (IOException e){
                logger.error(e);
                throw e;
            }
            logger.info("File transfer finished.");
            clientWriter.println("File was written successfully!");
            clientWriter.flush();
        }
    }

    @Override
    public void copy(File to) throws IOException {
        copy(to, DEFAULT_PORT);
    }
}
